package com.xuecheng.content.services.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XCPlusException;
import com.xuecheng.content.model.dto.SaveTeachPlanDto;
import com.xuecheng.content.model.dto.TeachPlanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.services.mapper.TeachplanMapper;
import com.xuecheng.content.services.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Override
    public List<TeachPlanDto> findTeachPlanTree(Long courseId) {

        return teachplanMapper.selectTreeNodes(courseId);
    }

    @Override
    public void saveTeachPlan(SaveTeachPlanDto saveTeachPlanDto) {

        //通过ID判断是新增还是修改
        Long teachPlanId = saveTeachPlanDto.getId();
        if (teachPlanId == null){

            //TODO 新增
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachPlanDto,teachplan);

            //确定排序字段,找到它的同级节点个数，排序字段就是个数+1
            Long parentId = saveTeachPlanDto.getParentid();
            Long courseId = saveTeachPlanDto.getCourseId();

            //TODO 得到计划总数
            int teachPlanCount = getTeachPlanCount(courseId, parentId);

            teachplan.setOrderby(teachPlanCount);

            int insertResult = teachplanMapper.insert(teachplan);

            if (insertResult <= 0){

                XCPlusException.cast("添加课程计划失败！");
            }
        }else {

            //TODO 修改
            Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
            //将参数复制到teachPlan
            BeanUtils.copyProperties(saveTeachPlanDto,teachplan);

            teachplanMapper.updateById(teachplan);
        }
    }

    private int getTeachPlanCount(Long courseId,Long parentId){

        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);

        Integer count = teachplanMapper.selectCount(queryWrapper);

        return count + 1;
    }
}
